package com.jfm.jfmm.collector.driver;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jfm.jfmm.collector.entity.collect.CollectParam;
import com.jfm.jfmm.collector.entity.collect.Param;
import com.jfm.jfmm.collector.entity.collect.Result;
import com.jfm.jfmm.collector.entity.collect.param.SNMPParam;
import com.jfm.jfmm.collector.entity.collect.result.SNMPResult;
import com.jfm.jfmm.collector.entity.device.Device;
import com.jfm.jfmm.collector.entity.template.CollectTemplate;
import com.jfm.jfmm.collector.entity.template.SNMP;
import com.jfm.jfmm.collector.enums.CollectorProtocol;
import com.jfm.jfmm.collector.enums.snmp.SNMPMethod;
import com.jfm.jfmm.collector.enums.snmp.SNMPProtocol;

import java.util.ArrayList;
import java.util.List;

/**
 * @author DYang
 * @since 2024-10-08 23:16
 * SNMP 协议采集驱动
 */
public abstract class SNMPDriver implements ACollectorDriver<SNMPParam, SNMPResult> {


    @Override
    public CollectorProtocol supportProtocol() {
        return CollectorProtocol.SNMP;
    }

    @Override
    public SNMPParam transformParam(Param reqParam) {
        if (reqParam instanceof SNMPParam) {
            return (SNMPParam) reqParam;
        }
        return null;
    }

    @Override
    public SNMPResult transformResult(Result result) {
        if (result instanceof SNMPResult) {
            return (SNMPResult) result;
        }
        return null;
    }

    @Override
    public List<CollectParam> buildCollectParam(Device device, CollectTemplate template) {
        List<CollectParam> paramList = new ArrayList<>();
        // SNMP 连接配置信息
        SNMP snmpInfo = device.getSnmp();
        SNMPProtocol protocol = SNMPProtocol.getVersion(snmpInfo.getVersion());

        // 从模板中获取采集项
        List<SNMP.Item> items = template.getSnmp().getItems();
        for (SNMP.Item item : items) {
            JSONObject data1 = JSONUtil.parseObj(snmpInfo);
            JSONObject data2 = JSONUtil.parseObj(item);
            data1.putAll(data2);
            SNMPParam snmpParam = JSONUtil.toBean(data1, SNMPParam.class);

            snmpParam.setProtocol(protocol);
            snmpParam.setMethod(SNMPMethod.getMethod(item.getMethod()));
            snmpParam.setMetricCode(item.getCode());
            snmpParam.setMetricId(this.buildSpanId(device, item));
            snmpParam.setMetricName(item.getName());
            snmpParam.setDeviceCode(device.getCode());


            CollectParam collectParam = new CollectParam();
            collectParam.setParam(snmpParam);
            collectParam.setProtocol(this.supportProtocol());
            paramList.add(collectParam);
        }

        return paramList;
    }
}
